<template>
    <el-form-item label="部门：">
        <el-cascader v-model="selectedDepartmentIds" :options="transformedAuthorityData" clearable
            expand-trigger="hover"
            :props="{ checkStrictly: true, value: 'value', label: 'label', children: 'children' }"
            @change="handleDepartmentChange" />
    </el-form-item>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import api from '@/api/index.js'; // 假设这是你的API模块

const props = defineProps({
    modelValue: {
        type: [String, Number],
        default: ''
    }
});

const emit = defineEmits(['getModelValue']);

const selectedDepartmentIds = ref([]);
const transformedAuthorityData = ref([]);
const authorityData = ref([]);

const transformAuthorityData = (data) => {
    return data.map(department => ({
        value: department.id,
        label: department.name,
        children: transformAuthorityData(department.childs || []),
    }));
};

const getAllauthorityData = async () => {
    try {
        const res = await api.authority.getAll();
        if (res.code === 0) {
            authorityData.value = res.data;
            transformedAuthorityData.value = transformAuthorityData(res.data);
        } else {
            ElMessage.error('获取部门数据失败');
        }
    } catch (error) {
        ElMessage.error('获取部门数据出错');
    }
};

const handleDepartmentChange = (value) => {
    const values = Array.isArray(value) ? value : [];
    const lastSelectedValue = values.length > 0 ? values[values.length - 1] : '';
    emit('getModelValue', lastSelectedValue);
};

onMounted(() => {
    getAllauthorityData();
});

// 初始化时设置选中的值
if (props.modelValue) {
    selectedDepartmentIds.value.push(props.modelValue);
}
</script>

<style scoped>
/* 可以在这里添加组件的样式 */
</style>